package com.dgut.staffmodule.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.dgut.common.util.ExtAjaxResponse;
import com.dgut.common.util.ExtJsonResult;
import com.dgut.common.util.ExtPageable;
import com.dgut.common.util.Gender;
import com.dgut.staffmodule.entity.Department;
import com.dgut.staffmodule.entity.Position;
import com.dgut.staffmodule.entity.Staff;
import com.dgut.staffmodule.entity.StaffEditDTO;
import com.dgut.staffmodule.entity.StaffQueryDTO;
import com.dgut.staffmodule.service.IDepartmentService;
import com.dgut.staffmodule.service.IStaffService;

import net.sf.json.util.JSONUtils;

@Controller
@RequestMapping("/staff")
public class StaffController {

	@Autowired
	private IStaffService staffService;
	@Autowired
	private IDepartmentService departmentService;

	/**
	 * 保存员工信息
	 *
	 * @param staffEditDTO
	 *            员工信息
	 */
	@RequestMapping("/save")
	public @ResponseBody ExtAjaxResponse save(@Validated StaffEditDTO staffEditDTO) {
		try {
			boolean res = staffService.save(staffEditDTO);
			if(res) {
				return new ExtAjaxResponse(true, "操作成功！");
			}else {
				return new ExtAjaxResponse(false, "操作失败！该用户名已存在！");
			}
		} catch (Exception e) {
			return new ExtAjaxResponse(false, "操作失败！");
		}
	}

	/**
	 * 更新员工信息
	 *
	 * @param staffEditDTO
	 *            员工信息
	 */
	@RequestMapping("/update")
	public @ResponseBody ExtAjaxResponse update(StaffEditDTO staffEditDTO) {// ,@RequestParam Long departmentId
		try {
			staffService.update(staffEditDTO);
			return new ExtAjaxResponse(true, "操作成功！");
		} catch (Exception e) {
			return new ExtAjaxResponse(false, "操作失败！");
		}
	}

	/**
	 * 删除员工信息
	 *
	 * @param id
	 *            前端传的id
	 */
	@RequestMapping("/deleteStaff")
	public @ResponseBody ExtAjaxResponse delete(@RequestParam Long id) {
		try {
			Staff staff = staffService.findOne(id);
			staffService.delete(staff);
			return new ExtAjaxResponse(true, "操作成功！");
		} catch (Exception e) {
			return new ExtAjaxResponse(false, "操作失败！");
		}
	}

	/**
	 * 批量员工信息
	 *
	 * @param ids
	 *            前端传的ids
	 */
	@RequestMapping("/deleteStaffs")
	public @ResponseBody ExtAjaxResponse deleteStaffs(@RequestParam Long[] ids) {
		try {
			List<Long> idLists = Arrays.asList(ids);
			/*
			 * if (null != idLists) { for (Long id : idLists) {
			 * departmentService.descCount(staffService.findOne(id).getDepartment().getId())
			 * ; } }
			 */
			staffService.delete(idLists);
			return new ExtAjaxResponse(true, "操作成功！");
		} catch (Exception e) {
			return new ExtAjaxResponse(false, "操作失败！");
		}
	}

	/**
	 * 查找一个员工信息
	 *
	 * @param id
	 *            前端传的id
	 */
	@RequestMapping("/findOne")
	public @ResponseBody Staff findOne(@RequestParam Long id) {
		Staff staff = staffService.findOne(id);

		return staff;
	}

	/**
	 * 查找所有员工信息
	 */
	@RequestMapping("/findAll")
	public @ResponseBody List<Staff> findAll() {
		List<Staff> lists = staffService.findAll();

		return lists;
	}

	/**
	 * 分页查找所有员工信息
	 * 
	 * @param staffQueryDTO
	 *            前端传的员工查找条件staffQueryDTO
	 * @param pageable
	 *            分页条件
	 */
	@RequestMapping("/findPage")
	public @ResponseBody Page<Staff> findPage(StaffQueryDTO staffQueryDTO, ExtPageable pageable) {
		Page<Staff> page = staffService.findPage(StaffQueryDTO.getSpecification(staffQueryDTO), pageable.getPageable());
		// System.out.println(page);
		return page;
	}

	/*
	 * public Long findDepartmentLeader(String userName) { Long id =
	 * staffService.findDepartmentLeader(userName); return id; }
	 */

	/**
	 * 批量导出员工信息
	 * 
	 * @param mFile
	 *            前端传的接受导出的excel文件
	 */
	@RequestMapping("/exportStaff")
	public @ResponseBody ExtAjaxResponse exportStaff(@RequestParam("filePath") MultipartFile mFile) {// @RequestParam
																										// String[]
																										// staffLists
		String filePath = mFile.getOriginalFilename();
		System.out.println(mFile.getName());
		System.out.println(filePath);

		// 第一步，创建一个webbook，对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();

		// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
		HSSFSheet sheet = wb.createSheet("员工");

		// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
		HSSFRow row = sheet.createRow((int) 0);
		// 第四步，创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		// style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

		HSSFCell cell = row.createCell((short) 0);
		cell.setCellValue("员工号");
		cell.setCellStyle(style);

		cell = row.createCell((short) 1);

		cell.setCellValue("姓名");
		cell.setCellStyle(style);
		cell = row.createCell((short) 2);

		cell.setCellValue("性别");
		cell.setCellStyle(style);
		cell = row.createCell((short) 3);

		cell.setCellValue("年龄");
		cell.setCellStyle(style);
		cell = row.createCell((short) 4);

		cell.setCellValue("手机号码");
		cell.setCellStyle(style);
		cell = row.createCell((short) 5);

		cell.setCellValue("出生日期");
		cell.setCellStyle(style);
		cell = row.createCell((short) 6);

		cell.setCellValue("地址");
		cell.setCellStyle(style);
		cell = row.createCell((short) 7);

		cell.setCellValue("学历");
		cell.setCellStyle(style);
		cell = row.createCell((short) 8);

		cell.setCellValue("入职日期");
		cell.setCellStyle(style);
		cell = row.createCell((short) 9);

		cell.setCellValue("爱好");
		cell.setCellStyle(style);
		cell = row.createCell((short) 10);

		cell.setCellValue("部门");
		cell.setCellStyle(style);
		cell = row.createCell((short) 11);

		cell.setCellValue("职位");
		cell.setCellStyle(style);
		cell = row.createCell((short) 12);

		Map<String, Object> paramMap = new HashMap<String, Object>();
		// 第五步，写入实体数据 实际应用中这些数据从数据库得到，
		List<Staff> staffList = staffService.findAll();

		Staff staff = null;
		for (int i = 0; i < staffList.size(); i++) {
			row = sheet.createRow((int) i + 1);
			staff = new Staff();
			staff = staffList.get(i);
			// 第四步，创建单元格，并设置值
			row.createCell((short) 0).setCellValue(staff.getId());
			row.createCell((short) 1).setCellValue(staff.getStaffName());

			String sex;
			if (staff.getSex().equals("Femal")) {
				sex = "女";
			} else {
				sex = "男";
			}

			row.createCell((short) 2).setCellValue(sex);
			row.createCell((short) 3).setCellValue(staff.getAge());
			row.createCell((short) 4).setCellValue(staff.getPhone());

			Date birthday = staff.getBirthday();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			String dateString = formatter.format(birthday);
			row.createCell((short) 5).setCellValue(dateString);
			row.createCell((short) 6).setCellValue(staff.getAddress());
			row.createCell((short) 7).setCellValue(staff.getEducation());

			Date inTime = staff.getInTime();
			dateString = formatter.format(inTime);
			row.createCell((short) 8).setCellValue(dateString);
			row.createCell((short) 9).setCellValue(staff.getHobby());
			row.createCell((short) 10).setCellValue(staff.getDepartment().getDeptName());
			row.createCell((short) 11).setCellValue(staff.getPosition());

		}
		// 第六步，将文件存到指定位置
		try {
			Map<String, Object> retMap = new HashMap<String, Object>();
			String resultStr = null;

			// String filePath = "E:/staff.xls";

			File file = new File("E:/" + filePath);
			// File file=new File("D:/TradeOrder.xls");

			if (!file.exists()) {
				try {
					file.createNewFile();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			FileOutputStream fout = new FileOutputStream(file);
			wb.write(fout);
			fout.close();
			retMap.put("result", true);
			resultStr = JSONUtils.convertToJavaIdentifier(resultStr);
			return new ExtAjaxResponse(true, "操作成功,已导出至" + "E:/" + filePath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ExtAjaxResponse(false, "操作失败！");
	}

	/**
	 * 批量导入员工信息
	 * 
	 * @param mFile
	 *            前端传的接受导入的excel文件
	 */
	@RequestMapping("/importStaff")
	public @ResponseBody ExtAjaxResponse importStaff(@RequestParam("filePath") MultipartFile mFile) throws Exception {

		InputStream is = mFile.getInputStream();
		HSSFWorkbook wb = new HSSFWorkbook(is);
		HSSFSheet sheet = wb.getSheetAt(0);
		int rowsNum = sheet.getLastRowNum();
		List<Staff> staffLists = new ArrayList<Staff>();
		System.out.println(rowsNum);

		for (int i = 1; i <= rowsNum; i++) {
			HSSFRow row1 = sheet.getRow(i);
			Staff staff = new Staff();
			staff.setStaffName(row1.getCell(0).getStringCellValue());
			staff.setPassword(row1.getCell(1).getStringCellValue());
			String sex = row1.getCell(2).getStringCellValue();
			if (sex.equals("男")) {
				staff.setSex(Gender.Male);
			} else {
				staff.setSex(Gender.Female);
			}
			staff.setAge((int) row1.getCell(3).getNumericCellValue());
			staff.setPhone(row1.getCell(4).getStringCellValue());
			staff.setBirthday(row1.getCell(5).getDateCellValue());
			staff.setAddress(row1.getCell(6).getStringCellValue());
			staff.setEducation(row1.getCell(7).getStringCellValue());
			staff.setInTime(row1.getCell(8).getDateCellValue());
			staff.setHobby(row1.getCell(9).getStringCellValue());
			String deptName = row1.getCell(10).getStringCellValue();
			Department department = departmentService.findByDeptName(deptName);
			staff.setDepartment(department);
			staff.setPosition(row1.getCell(11).getStringCellValue());
			staffLists.add(staff);
			System.out.println(i);
		}

		try {
			
			Boolean res = staffService.multiSave(staffLists);
			if(res) {
				return new ExtAjaxResponse(true, "导入成功");
			}else {
				return new ExtAjaxResponse(false, "操作失败,存在用户名相同的员工!");
			}
		} catch (Exception e) {
			return new ExtAjaxResponse(false, "操作失败,存在用户名相同的员工!");
		}

	}

	// @SuppressWarnings("null")
	@RequestMapping("/totalSex")
	public @ResponseBody int[] totalSex() {
		int maleCount = staffService.totalSex("男");
		int femaleCount = staffService.findAll().size() - maleCount;
		int[] sex = { maleCount, femaleCount };
		return sex;
	}
	
	@RequestMapping("/findBySex")
	public @ResponseBody ExtJsonResult<Staff> findBySex(@RequestParam String sex){
		List<Staff> staffLists = staffService.findBySex2(sex);
		return new ExtJsonResult<Staff>(staffLists);
	}
}
